/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.war.session;

import com.ejb.metier.IBookManager;
import com.ejb.persistence.Book;
import com.ejb.persistence.Invoice;
import com.war.helpers.HelperDebug;
import com.war.helpers.HelperNavigation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.ejb.EJB;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author Ambroise
 */
@ManagedBean
@SessionScoped
public class CartSession {

    @EJB
    private IBookManager bookManagerBean;
    
    private ELContext elContext = FacesContext.getCurrentInstance().getELContext();
    private UserSession session = (UserSession) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "userSession");
    private HelperNavigation navigation = (HelperNavigation) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "helperNavigation");
        
    private List<Invoice> invoices;
    /**
     * Creates a new instance of CartSession
     */
    public CartSession() {
    }

    public List<Invoice> getInvoices() {
        return invoices;
    }

    public void setInvoices(List<Invoice> invoices) {
        this.invoices = invoices;
    }
    
    public String addInvoice(Book book, int quantity){
        if (this.invoices == null){
            this.invoices = new ArrayList<Invoice>();
        }
        
        if (quantity <= book.getStock()){
            int quantitySessionCart = 0;
            boolean exists = false;
            for (Invoice in:this.invoices){
                if (in.getBook().getId() == book.getId()){
                    exists = true;
                    
                    quantitySessionCart = in.getQuantity() + quantity;
                    if(quantitySessionCart > book.getStock()){
                        in.setQuantity(book.getStock());
                        HashMap<String, Object> m = new HashMap<String, Object>();
                        m.put("type", "info");
                        m.put("message", "La quantité du livre \"" + book.getTitle() + "\" dépassait son stock disponible, elle a été ajustée. <a href='"+navigation.getUrl("cart")+"' class='orange b'>Modifier quantité</a>");
                        ArrayList<HashMap<String, Object>> messages = session.getMessages();
                        messages.add(m);
                        session.setMessages(messages); 
                    } else {
                        in.setQuantity(quantitySessionCart);
                    }
                }
            }

            // If the quantity was updated.
            if(quantitySessionCart <= book.getStock()){
                if(!exists){
                    Invoice invoice = new Invoice();
                    invoice.setBook(book);
                    invoice.setQuantity(quantity);
                    this.invoices.add(invoice);

                    HelperDebug.addMessage("Le livre \""+book.getTitle()+"\" a été ajouté à votre panier en "+quantity+" exemplaire"+((quantity > 1)? "s" : "")+". <a href='"+navigation.getUrl("cart")+"' class='orange b'>Modifier quantité</a>", "success");
                }else{
                    HelperDebug.addMessage(quantity+" exemplaire"+((quantity > 1)? "s" : "")+" du livre \""+book.getTitle()+"\" "+((quantity > 1)? "ont été ajoutés" : "a été ajouté")+" à votre panier. ("+quantitySessionCart+" exemplaires au total) <a href='"+navigation.getUrl("cart")+"' class='orange b'>Modifier quantité</a>", "success");
                }
            }
        }else{
            HelperDebug.addMessage("Il n'y a plus de stock pour le livre \""+book.getTitle()+"\".", "warning");
        }
        
        // Retour vers la page en cours.
        return "";
        
    }
    
    public String removeInvoice(Invoice invoice){
        if(this.invoices.contains(invoice)){
            this.invoices.remove(invoice);
        }
        return "cart?faces-redirect=true";
    }
    
    public Float getTotalPrice(){
        Float total = 0f;
        
        for (Invoice in:invoices){
            total += in.getQuantity() * in.getBook().getPrice();
        }
        
        return total;
    }
    
    public String updateCart(){
        
        boolean qty = false;
        
        for (Invoice in:this.invoices){
            Book b = bookManagerBean.getBookById(in.getBook().getId());
            if (in.getQuantity() > b.getStock()){
                in.setQuantity(b.getStock());
                qty = true;
            }
        }
        if (qty){
            HashMap<String, Object> m = new HashMap<String, Object>();
            m.put("type", "info");
            m.put("message", "La quantité d'un ou plusieurs articles dépassait le stock disponible, elle a été ajustée.");
            ArrayList<HashMap<String, Object>> messages = session.getMessages();
            messages.add(m);
            session.setMessages(messages); 
        }
        
        return "cart";
    }
}
